package vv.lines.core;

import vv.lines.core.context.IContext;
import vv.lines.view.TextDialogView;
import vv.lines.view.View;
import vv.lines.view.WindowView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.logging.Logger;

import static java.util.logging.Level.SEVERE;
import static vv.lines.utils.LinesConstants.NEW_LINE;

/**
 * @author vpotapenko
 */
public class TextWindow extends VisualObject {

    private static final Logger logger = Logger.getLogger(TextWindow.class.getName());

    private String text;

    public TextWindow(String title, IContext context) {
        super(context);
        getView().setTitle(title);
    }

    public void setTextResource(String resource) {
        InputStream inputStream = getClass().getResourceAsStream(resource);
        try {
            initText(inputStream);
            getView().setText(text);
        } catch (IOException e) {
            logger.log(SEVERE, e.getMessage(), e);
        }
    }

    private void initText(InputStream inputStream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String str;
        while ((str = reader.readLine()) != null) {
            sb.append(str);
            sb.append(NEW_LINE);
        }

        text = sb.toString();
    }

    public void show(WindowView owner) {
        getView().show(owner);
    }

    @Override
    public TextDialogView getView() {
        return (TextDialogView) super.getView();
    }

    @Override
    protected View createView() {
        return getViewFactory().createTextWindowView();
    }

    public void setTextSize(int width, int height) {
        getView().setTextSize(width, height);
    }
}
